/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.organization;

import com.alibaba.fastjson.JSONObject;
import com.qinyeit.serviceapp.entity.Branch;
import com.qinyeit.serviceapp.entity.Department;
import com.qinyeit.serviceapp.entity.DishesStore;
import com.qinyeit.serviceapp.entity.District;
import com.qinyeit.serviceapp.entity.enums.Industries;
import com.qinyeit.serviceapp.entity.enums.PropType;
import com.qinyeit.serviceapp.entity.enums.RoleType;
import com.qinyeit.serviceapp.entity.enums.State;
import com.qinyeit.serviceapp.entity.system.ManagementRole;
import com.qinyeit.serviceapp.exception.BusinessRunTimeException;
import com.qinyeit.serviceapp.service.dishes.DishesStoreService;
import com.qinyeit.serviceapp.service.organization.BranchService;
import com.qinyeit.serviceapp.service.organization.DistrictService;
import com.qinyeit.serviceapp.service.organization.PrivilegeTemplateService;
import com.qinyeit.serviceapp.service.system.ManagementRoleService;
import com.qinyeit.serviceapp.service.thirdpart.PlatformApiServiceImpl;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.entity.search.SearchOperator;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: BranchsController <br/>
 * Function: branch [分店] <br/>
 * date: 2018-11-21 15:03:05 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/organization/branchs")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_branch:read",name ="分店",deleteAble = false)
public class BranchsController extends BaseManagementController{

	@Autowired
	private BranchService branchService;
	@Autowired
    private DistrictService districtService;
	@Autowired
    private PrivilegeTemplateService privilegeTemplateService;
	@Autowired
    private PlatformApiServiceImpl platformApiService;
	@Autowired
    private ManagementRoleService managementRoleService;
	@Autowired
    private DishesStoreService dishesStoreService;

	private final String [] keys = {"id","name","districtId","industry","propType","templateId","phone","telephone","location","address",
            "regCode","username","password","state","operatorName","createAt","templateName","districtName","linker"};

    @RequiresPermissions("management_branch:show")
    @PermissionInfo(code = "management_branch:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable){
        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
        Page<Branch> branchPage = branchService.findAll(searchable);
        if(CollectionUtils.isNotEmpty(branchPage.getContent())){
            for (Branch branch : branchPage.getContent()) {
                if(branch.getTemplateId()!=null){
                    if(privilegeTemplateService.findById(branch.getTemplateId())!=null){
                        branch.setTemplateName(privilegeTemplateService.findById(branch.getTemplateId()).getName());
                    }
                }if(branch.getDistrictId()!=null){
                    if(districtService.findById(branch.getDistrictId())!=null){
                        branch.setDistrictName(districtService.findById(branch.getDistrictId()).getName());
                    }
                }
            }
        }
        QyMap map = QyMap.map("branchPage",JSONUtils.include(branchPage,new Class[]{State.class,PropType.class}, keys));
        initFormDate(map);
        return ok("查询成功", map);
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(){
        QyMap map=QyMap.NEW();
        map.setv("branch",JSONUtils.include(new Branch(), keys));
        initFormDate(map);
        //获取行业
//        map.setv("industries",platformApiService.queryIndustries());
        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_branch:create")
    @PermissionInfo(code = "management_branch:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@ModelAttribute @Valid Branch branch, BindingResult bindingResult){
//        if(branchService.exists(buildExists(null, "no", branch.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        log.info("branch:{}",branch);
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }

        if(StringUtils.isBlank(branch.getName())){
            throw new BusinessRunTimeException("请填写门店名称",10001);
        }
        boolean boo = branchService.exists(SearchableUtils.buildExists(branch.getId(), "name", branch.getName()));
        if(boo){
            return fail("名称已经存在");
        }
        if(StringUtils.isBlank(branch.getRegCode())){
            throw new BusinessRunTimeException("请填写激活码",10002);
        }
        if(StringUtils.isBlank(branch.getUsername())){
            throw new BusinessRunTimeException("请填写用户名",10003);
        }
        if(branchService.exists(SearchableUtils.buildExists(branch.getId(), "username", branch.getUsername()))){
            return fail("用户名已存在");
        }
        if (StringUtils.isBlank(branch.getPassword())){
            throw new BusinessRunTimeException("请填写密码",10004);
        }
        if (StringUtils.isBlank(branch.getPhone())){
            throw new BusinessRunTimeException("手机号不能为空",10005);
        }
        if(StringUtils.isBlank(branch.getLocation())){
            throw new BusinessRunTimeException("请填写地理位置",10006);
        }

        String password = branch.getPassword();
        branch.setMerchantGroupId(CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        branch.setOperatorName(CurrentAccountUtils.getAuthenticatedEmployeeName());

        //更新分店
        branch = branchService.updateBranch(branch,password);
        log.info("更新分店结束--------------------");

        log.info("保存成功--------------------");
        return ok("保存成功");
    }


    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute Branch branch){
        return ok("查询成功", JSONUtils.include(branch, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute Branch branch){
        QyMap map=QyMap.NEW();
        if (branch.getDistrictId()!=null){
            branch.setDistrictName(districtService.findById(branch.getDistrictId()).getParentId().toString());
        }
        map.setv("branch",JSONUtils.include(branch, keys));
        initFormDate(map);
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_branch:update")
    @PermissionInfo(code = "management_branch:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@ModelAttribute @Valid Branch branch,BindingResult bindingResult){
//        if(branchService.exists(buildExists(null, "no", branch.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        if(StringUtils.isBlank(branch.getName())){
            return fail("请填写门店名称");
        }
        if(branchService.exists(SearchableUtils.buildExists(branch.getId(), "name", branch.getName()))){
            return fail("名称已经存在");
        }

        if (StringUtils.isBlank(branch.getPhone())){
            return fail("手机号不能为空");
        }
        if(StringUtils.isBlank(branch.getLocation())){
            return fail("请填写地理位置");
        }

        if(StringUtils.isNotBlank(branch.getPassword())){
            if(!StringUtils.equals(branch.getPassword(),branch.getPasswordConfirm())){
                return fail("两次密码不一致");
            }
        }

        branch.setMerchantGroupId(CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        branch.setOperatorName(CurrentAccountUtils.getAuthenticatedEmployeeName());

        //修改单店数据
        branchService.updateBranchData(branch);

        return ok("更新成功", null);
    }


    /**
     * 关联门店
     * @param branch
     * @param bindingResult
     * @return
     */
//    @RequiresPermissions("management_branch:relevance")
//    @PermissionInfo(code = "management_branch:relevance",name ="关联门店",deleteAble = false)
    @PostMapping("/relevance")
    public ResponseResult<String> relevance(@ModelAttribute @Valid Branch branch, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }

        return ok("查询成功");

    }

    /**
     * 关联门店 下一步 验证用户名和密码
     * @param branch
     * @param bindingResult
     * @return
     */
//    @RequiresPermissions("management_branch:verify")
//    @PermissionInfo(code = "management_branch:verify",name ="验证",deleteAble = false)
    @PostMapping("/verify")
    public ResponseResult<String> verify(@ModelAttribute @Valid Branch branch, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        QyMap map = branchService.verify(branch);
        return ok("验证成功",map);
    }

    /**
     * 关联门店 保存数据
     * @param
     * @return
     */
    @RequiresPermissions("management_branch:relevance")
    @PermissionInfo(code = "management_branch:relevance",name ="关联门店",deleteAble = false)
    @PostMapping("/saveRelevance")
    public ResponseResult<String> saveRelevance(@RequestBody JSONObject data){
        branchService.saveRelevance(data,CurrentAccountUtils.getAuthenticatedMerchantGroupID(),CurrentAccountUtils.getAuthenticatedEmployeeName());
        return ok("关联成功");

    }


    /**
     * 验证短信验证码
     * @param
     * @return
     */
//    @RequiresPermissions("management_branch:saveRelevance")
//    @PermissionInfo(code = "management_branch:saveRelevance",name ="关联门店",deleteAble = false)
    @GetMapping("/verifySmsCode")
    public ResponseResult<String> verifySmsCode(String phone,String code){
        branchService.verifySmsCode(phone,code);
        return ok("验证成功");

    }

    /**
     * 导出excel
     * @param
     * @return
     */
//    @RequiresPermissions("management_branch:exportExcel")
//    @PermissionInfo(code = "management_branch:exportExcel",name ="导出excel",deleteAble = false)
    @GetMapping("/exportExcel")
    public ResponseResult<String> exportExcel(Long merchantId){

        return ok("导出成功");
    }




    @RequiresPermissions("management_branch:destory")
    @PermissionInfo(code = "management_branch:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        branchService.logicDelete(id);
        return ok("删除成功", null);
    }


    /**
     * 解绑门店 验证
     * @param data
     * @return
     */
//    @RequiresPermissions("management_branch:relevance")
//    @PermissionInfo(code = "management_branch:relevance",name ="关联门店",deleteAble = false)
    @PostMapping("/unRelevanceValidate")
    public ResponseResult<String> unRelevanceValidate(@RequestBody JSONObject data){

        QyMap map = branchService.unRelevanceValidate(data,CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        return ok("验证成功",map);

    }


    /**
     * 解绑门店 解绑
     * @param data
     * @return
     */
    @RequiresPermissions("management_branch:unRelevance")
    @PermissionInfo(code = "management_branch:unRelevance",name ="关联门店",deleteAble = false)
    @PostMapping("/unRelevance")
    public ResponseResult<String> unRelevance(@RequestBody JSONObject data){
        branchService.unRelevance(data,CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        return ok("解绑成功");

    }


    /**
     *  获取某行业的门店
     * @param storeId
     *
     * @return
     */
    @GetMapping("/getBranchs")
    public ResponseResult<String> getBranchs(Long storeId){
        DishesStore store = dishesStoreService.findById(storeId);
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchFilter("industry", SearchOperator.eq, store.getIndustry().getText());
        log.info(">>>>>>>>>>>>> : {}",store.getIndustry().getText());
        List<Branch> branchList = branchService.findWithSort(searchable);
        if (CollectionUtils.isEmpty(branchList)){
            return ok("查询成功",null);
        }
        List<Long> ids = branchList.stream().map(x->x.getId()).collect(Collectors.toList());
        log.info("ids >>>>>>>>>>: {}",ids);

        List<District> districtList = districtService.getBuildTree(CurrentAccountUtils.getAuthenticatedMerchantGroupID(),true,ids,true);
        return ok("查询成功",districtList);

    }


    /**
     * 修改状态
     *
     * @param id
     * @return
     */
    @RequiresPermissions("management_branch:updateState")
    @PermissionInfo(code = "management_branch:updateState",name ="修改状态",deleteAble = false)
    @GetMapping("/updateState")
    public ResponseResult<String> updateState(Long id){
        Branch branch = branchService.findById(id);
        if(branch.getState()==State.NORMAL){
            branch.setState(State.DISABLED);
        }else {
            branch.setState(State.NORMAL);
        }
        branch.setOperatorName(CurrentAccountUtils.getAuthenticatedEmployeeName());
        branchService.update(branch);
        return ok("操作成功", null);
    }



    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            Branch branch = branchService.findById(Long.valueOf(id));
            model.addAttribute(branch);
        }
    }

    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){
        //区域
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("parentId_ne",0);
        List<District> districtList = districtService.findWithSort(searchable);
        qyMap.setv("districtList",districtList);
        qyMap.setv("states", State.values());
        //门店属性
        qyMap.setv("propTypes", PropType.values());
        //权限模板
//        searchable = SearchableUtils.newSearchableWithMerchantFilter();
//        List<PrivilegeTemplate> templateList = privilegeTemplateService.findWithSort(searchable);
//        qyMap.setv("templateList",JSONUtils.include(templateList,"id","name","codes","def","operatorName","createAt"));
        searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("type_eq", RoleType.BRANCHROLE);
        searchable.addSearchParam("code_ne","administrator");
        List<ManagementRole> roleList = managementRoleService.findWithSort(searchable);
        qyMap.setv("roleList",JSONUtils.include(roleList,"id","name","code","type","description"));

        qyMap.setv("industries",platformApiService.queryIndustries());




    }

}